package com.mvp.lt.airlineview;

import android.annotation.TargetApi;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.location.LocationManager;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.multidex.MultiDex;

import com.amap.api.maps.model.LatLng;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.ToastUtils;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.tencent.bugly.beta.interfaces.BetaPatchListener;
import com.tencent.bugly.beta.upgrade.UpgradeListener;
import com.tencent.bugly.beta.upgrade.UpgradeStateListener;

import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * Created by ${LiuTao}.
 * User: Administrator
 * Name: AirLineView
 * functiona:
 * Date: 2019/5/16 0016
 * Time: 下午 18:15
 */
public class App extends Application {
    private LocationManager mLocationManager;
    private LatLng latLng;
    private static Context sContext;
    public static App application;
    private String TAG = "App";
    public static final String APP_ID = "1638ccad67";
    public static final String APP_CHANNEL = "DEBUG"; // TODO 自定义渠道

    @Override
    public void onCreate() {
        super.onCreate();
        MultiDex.install(this);
        application = this;
        sContext = this;
        CrashHandler.getInstance().init(getApplicationContext());
        initNet();
        initNotificationManager();
        initBugly();
    }

    public LocationManager getLocationManager() {
        return mLocationManager;
    }

    public void setLocationManager(LocationManager locationManager) {
        mLocationManager = locationManager;
    }

    public LatLng getLatLng() {
        return latLng;
    }

    public void setLatLng(LatLng latLng) {
        this.latLng = latLng;
    }

    private void initNet() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        //初始化网络框架
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(loggingInterceptor);
        //网络拦截器
        builder.addNetworkInterceptor(new NetInterceptor("网络拦截器：", false));
        //全局的读取超时时间
        builder.readTimeout(1000, TimeUnit.SECONDS);
        //全局的写入超时时间
        builder.writeTimeout(1000, TimeUnit.SECONDS);
        //全局的连接超时时间
        builder.connectTimeout(7, TimeUnit.SECONDS);
        //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));
        OkGo.getInstance().init(this)                       //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置将使用默认的
                .setCacheMode(CacheMode.NO_CACHE)    //全局统一缓存模式，默认不使用缓存，可以不传
                .setRetryCount(0)
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE);
    }

    private void initNotificationManager() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "updateApp";
            String channelName = "升级程序";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            createNotificationChannel(channelId, channelName, importance);
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

    public static App getInstance() {
        return application;
    }

    public static Context getContext() {
        return sContext;
    }

    private void initBugly() {
        setStrictMode();
        Beta.autoInit = true;
        Beta.autoCheckUpgrade = false;
        Beta.upgradeCheckPeriod = 30 * 1000;
        Beta.initDelay = 5 * 1000;
        Beta.largeIconId = R.mipmap.ic_launcher;
        Beta.smallIconId = R.mipmap.ic_launcher;
        Beta.defaultBannerId = R.mipmap.ic_launcher;
        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        Beta.showInterruptedStrategy = true;
        Beta.upgradeDialogLayoutId = R.layout.app_upgrade_dialog;
        Beta.tipsDialogLayoutId = R.layout.app_update_tips_dialog;
        Beta.enableNotification = true;
        Beta.autoDownloadOnWifi = true;
        // 设置是否开启热更新能力，默认为true
        Beta.enableHotfix = true;
        // 设置是否自动下载补丁
        Beta.canAutoDownloadPatch = true;
        // 设置是否提示用户重启
        Beta.canNotifyUserRestart = true;
        // 设置是否自动合成补丁
        Beta.canAutoPatch = true;
        /**
         *  全量升级状态回调
         */
        Beta.upgradeStateListener = new UpgradeStateListener() {
            @Override
            public void onUpgradeSuccess(boolean isManual) {
                if (isManual) {

                    LogUtil.e(TAG, "检测到新版本");
                }
                //EventBus.getDefault().post(new AppUpdateEvent());
            }

            @Override
            public void onUpgradeFailed(boolean isManual) {
                if (isManual) {
                    ToastUtils.showToast("网络连接失败");
                }

            }

            @Override
            public void onUpgrading(boolean isManual) {
                if (isManual) {
                    ToastUtils.showToast("正在检测更新...");
                }
            }

            @Override
            public void onDownloadCompleted(boolean b) {
                LogUtil.e(TAG, "下载完成" + b);
            }

            @Override
            public void onUpgradeNoVersion(boolean isManual) {
                if (isManual) {
                    ToastUtils.showToast("已经是最新版本");
                }
            }
        };
        /*在application中初始化时设置监听，监听策略的收取*/
        Beta.upgradeListener = new UpgradeListener() {
            /**
             * 接收到更新策略
             * @param ret  0:正常 －1:请求失败
             * @param strategy 更新策略
             * @param isManual true:手动请求 false:自动请求
             * @param isSilence true:不弹窗 false:弹窗
             * @return 是否放弃SDK处理此策略，true:SDK将不会弹窗，策略交由app自己处理
             */
            @Override
            public void onUpgrade(int ret, UpgradeInfo strategy, boolean isManual, boolean isSilence) {
                LogUtil.e(TAG, "---onUpgrade---");
                if (strategy != null) {
                    Beta.getUpgradeInfo();
                    AppUpdateService.getInstance().showDownloadAppView((AppCompatActivity) AppManager.getAppManager().currentActivity());
                } else {
                    UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
                    if (upgradeInfo != null) {
                        LogUtil.e(TAG, "---onUpgrade---本地：" + upgradeInfo.versionName);
                    }
                }
            }
        };
        /**
         * 补丁回调接口，可以监听补丁接收、下载、合成的回调
         */
        // 补丁回调接口
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFile) {
                LogUtil.e(TAG, "补丁下载地址:" + patchFile);

            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
                LogUtil.e(TAG, "补丁下载中:" + String.format(Locale.getDefault(), "%s %d%%",
                        Beta.strNotificationDownloading,
                        (int) (totalLength == 0 ? 0 : savedLength * 100 / totalLength)));

            }

            @Override
            public void onDownloadSuccess(String msg) {
                LogUtil.e(TAG, "补丁下载成功");
                // Toast.makeText(getApplication(), "补丁下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadFailure(String msg) {
                LogUtil.e(TAG, "补丁下载失败:" + msg);
                // Toast.makeText(getApplication(), "补丁下载失败", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onApplySuccess(String msg) {
                LogUtil.e(TAG, "补丁应用成功");
                // Toast.makeText(getApplication(), "补丁应用成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplyFailure(String msg) {
                LogUtil.e(TAG, "补丁应用失败:" + msg);
                // Toast.makeText(getApplication(), "补丁应用失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPatchRollback() {

            }
        };

        long start = System.currentTimeMillis();
        Bugly.setUserId(this, "falue");
        Bugly.setUserTag(this, 123456);
        Bugly.putUserData(this, "key1", "123");
        Bugly.setAppChannel(this, "官方");
        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId,调试时将第三个参数设置为true
        Bugly.init(this, APP_ID, true);
        long end = System.currentTimeMillis();
        Log.e("init time--->", end - start + "ms");
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
//        Beta.installTinker();
    }


    @TargetApi(9)
    protected void setStrictMode() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }
}
